package com.cygsunri.report.task;

import com.cygsunri.report.entity.GeneralReport;
import com.cygsunri.report.entity.ReportTime;
import com.cygsunri.report.service.EmailService;
import com.cygsunri.report.service.GeneralReportService;
import com.cygsunri.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
@ConditionalOnProperty(prefix = "task.report", name = "open", havingValue = "true")
@PropertySource(name = "application.yml", value = {"classpath:application.yml"}, ignoreResourceNotFound = false, encoding = "UTF-8")
public class ReportTimedPrintingTask {

    @Autowired
    private GeneralReportService generalReportService;

    @Autowired
    private EmailService emailService;

    @Value("${spring.mail.to}")
    private String to;

    /**
     * 日报表定时打印
     */
    @Scheduled(cron = "${task.report.day.cron}")
    public void dayReportPrinting() {
        String date = DateUtil.yesterday();
        List<GeneralReport> reports = generalReportService.getGeneralReportByReportTimeAndIsTimedPrinting(ReportTime.DAY.getName(), Boolean.TRUE);
        reports.forEach(report -> {
            report.setDate(date);
            try {
                generalReportService.generateReport(report);
                String excelFileName = System.getProperty("java.io.tmpdir") + File.separator + report.getFileName();
                File source = new File(excelFileName);
                int index = report.getFileName().indexOf(".");
                String copyFileName = System.getProperty("java.io.tmpdir") + File.separator + report.getFileName().substring(0, index) + "-" + date + ".xls";
                File dest = new File(copyFileName);
                copyFileUsingFileChannels(source, dest);
                emailService.sendRichMail(to, report.getName(), "", dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 月报表定时打印
     */
    @Scheduled(cron = "${task.report.month.cron}")
    public void monthReportPrinting() {
        String month = DateUtil.beforeMonth(LocalDate.now().format(DateUtil.ym));
        List<GeneralReport> reports = generalReportService.getGeneralReportByReportTimeAndIsTimedPrinting(ReportTime.MONTH.getName(), Boolean.TRUE);
        reports.forEach(report -> {
            report.setDate(month);
            try {
                generalReportService.generateReport(report);
                String excelFileName = System.getProperty("java.io.tmpdir") + File.separator + report.getFileName();
                File source = new File(excelFileName);
                int index = report.getFileName().indexOf(".");
                String copyFileName = System.getProperty("java.io.tmpdir") + File.separator + report.getFileName().substring(0, index) + "-" + month + ".xls";
                File dest = new File(copyFileName);
                copyFileUsingFileChannels(source, dest);
                emailService.sendRichMail(to, report.getName(), "", dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 年报表定时打印
     */
    @Scheduled(cron = "${task.report.year.cron}")
    public void yearReportPrinting() {
        String year = DateUtil.lastYear(LocalDateTime.now()).format(DateUtil.y);
        List<GeneralReport> reports = generalReportService.getGeneralReportByReportTimeAndIsTimedPrinting(ReportTime.YEAR.getName(), Boolean.TRUE);
        reports.forEach(report -> {
            report.setDate(year);
            try {
                generalReportService.generateReport(report);
                String excelFileName = System.getProperty("java.io.tmpdir") + File.separator + report.getFileName();
                File source = new File(excelFileName);
                int index = report.getFileName().indexOf(".");
                String copyFileName = System.getProperty("java.io.tmpdir") + File.separator + report.getFileName().substring(0, index) + "-" + year + ".xls";
                File dest = new File(copyFileName);
                copyFileUsingFileChannels(source, dest);
                emailService.sendRichMail(to, report.getName(), "", dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    private void copyFileUsingFileChannels(File source, File dest) throws IOException {
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            inputChannel = new FileInputStream(source).getChannel();
            outputChannel = new FileOutputStream(dest).getChannel();
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
        } finally {
            inputChannel.close();
            outputChannel.close();
        }
    }
}
